package com.hkts.management.message.msg.service.serviceimpl;

import cn.hutool.core.date.DateUnit;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hkts.management.common.mq.ChatType;
import com.hkts.management.common.mq.IMessage;
import com.hkts.management.common.utils.SnowFlakeUtil;
import com.hkts.management.message.constants.MessageConstants;
import com.hkts.management.message.msg.entity.MsgRecord;
import com.hkts.management.message.msg.entity.MsgTemplate;
import com.hkts.management.message.msg.mapper.MsgTemplateMapper;
import com.hkts.management.message.msg.sendUtil.MsgSendUtil;
import com.hkts.management.message.msg.sendUtil.NettySendUtil;
import com.hkts.management.message.msg.sendUtil.ResultMsg;
import com.hkts.management.message.msg.service.IMsgTemplateService;
import com.hkts.management.message.nettyhandler.MyChannelHandlerPool;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.text.StringSubstitutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zy
 * @since 2021-05-10
 */
@Slf4j
@Service
@Transactional
public class MsgTemplateServiceImpl extends ServiceImpl<MsgTemplateMapper, MsgTemplate> implements IMsgTemplateService {


    @Autowired
    private MsgTemplateMapper msgTemplateMapper;
    @Autowired
    private MsgRecordServiceImpl msgRecordService;
   @Autowired
   private MsgSendUtil msgSendUtil;


    @Override
    public IPage<MsgTemplate> selectPage(Page<MsgTemplate> page, MsgTemplate msgTemplate) {
        QueryWrapper<MsgTemplate> query = Wrappers.query();
        QueryWrapper<MsgTemplate> entityWrapper = getEntityWrapper(query, msgTemplate);
        return msgTemplateMapper.selectPage(page, entityWrapper);
    }


    @Override
    public List<MsgTemplate> selectList(MsgTemplate msgTemplate) {
        QueryWrapper<MsgTemplate> query = Wrappers.query();
        QueryWrapper<MsgTemplate> entityWrapper = getEntityWrapper(query, msgTemplate);
        return msgTemplateMapper.selectList(entityWrapper);
    }

    /**
     * 公共查询条件
     *
     * @param entityWrapper
     * @return
     */
    public QueryWrapper<MsgTemplate> getEntityWrapper(QueryWrapper<MsgTemplate> entityWrapper, MsgTemplate msgTemplate) {
        //条件拼接
        if (StringUtils.isNotBlank(msgTemplate.getSmsSend())) {
            entityWrapper.like(MsgTemplate.SMS_SEND, msgTemplate.getSmsSend());
        }
        if (StringUtils.isNotBlank(msgTemplate.getTitle())) {
            entityWrapper.like(MsgTemplate.TITLE, msgTemplate.getTitle());
        }
        if (StringUtils.isNotBlank(msgTemplate.getRemark())) {
            entityWrapper.like(MsgTemplate.REMARK, msgTemplate.getRemark());
        }
        return entityWrapper;
    }

    public void sendSmsMessage(IMessage iMessage) {
        //获取消息模板
        QueryWrapper<MsgTemplate> query = Wrappers.query();
        query.lambda().eq(MsgTemplate::getSiteCode,iMessage.getMsgCode());
        MsgTemplate msgTemplate=msgTemplateMapper.selectOne(query);
        //拼接推送消息
//        Map<String, Object> params= BeanConvertUtils.convertBean(param.get("templateData"),Map.class);
        Map<String, Object> params= iMessage.getParam();
//        String sms=MessageFormat.format(msgTemplate.getSmsSend(),  array);
        String sms=msgTemplate.getSmsSend();
        if(params!=null){
            sms= StringSubstitutor.replace(msgTemplate.getSmsSend(), params);
        }

        //保存推送消息

        MsgRecord msgRecord=new MsgRecord();
        msgRecord.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
        msgRecord.setMessageId(iMessage.getMessageId());
        msgRecord.setFromUserId(iMessage.getFromUserId());
        msgRecord.setToUserId(iMessage.getToUserId());
        msgRecord.setSmsType(msgTemplate.getSmsType());
        msgRecord.setChatType(iMessage.getChatType());
        msgRecord.setMsgType(iMessage.getMsgType());
        msgRecord.setContent(sms);
        msgRecord.setExtras(JSONObject.toJSONString(iMessage.getExtras()));
        msgRecord.setTitle(msgTemplate.getTitle());
        msgRecord.setSiteCode(msgTemplate.getSiteCode());
        msgRecord.setIsRead(0);
        msgRecord.setOrderId(iMessage.getExtras().getOrderId());
        int recordCount= msgRecordService.getRecordCount(iMessage.getMessageId());
        if(recordCount==0){
            msgRecordService.save(msgRecord);
        }
        log.info("组装发送消息{}",msgRecord);
        ResultMsg resultMsg=new ResultMsg();
        resultMsg.setCode(MessageConstants.SUBNEWS);
        resultMsg.setMessage(msgRecord);
        //TODO 调取推送接口
        if (iMessage.getChatType().equals(ChatType.BROADCAST.getIndex())){
            //广播
            NettySendUtil.sendAllMessage(resultMsg);
        }else if (iMessage.getChatType().equals(ChatType.MULTICAST.getIndex())){
            //组播
        }else if (iMessage.getChatType().equals(ChatType.UNICAST.getIndex())){
            //单播
            ChannelHandlerContext ctx=NettySendUtil.Verification(iMessage.getToUserId());
            if(ctx==null){

                log.info("没有获取到当前用户链接{}==>所有连接channel{}",iMessage.getToUserId(),NettySendUtil.getAllChannel());
                return;
            }
            NettySendUtil.sendPointMessage(resultMsg,ctx);
        }else if (iMessage.getChatType().equals(ChatType.WINXIN.getIndex())){
            //微信
            msgSendUtil.sendMessageByUserId(iMessage.getToUserId(),sms);
        }else {
            //其他情况
            log.warn("异常消息拦截：" + iMessage.toString());
        }

        //发送下标
        sendSubscript(iMessage.getToUserId());
    }
//    public void sendSmsMessage(Map<String, Object> param) {
//        //获取消息模板
//        QueryWrapper<MsgTemplate> query = Wrappers.query();
//        query.lambda().eq(MsgTemplate::getSiteId,param.get("siteId"));
//        MsgTemplate msgTemplate=msgTemplateMapper.selectOne(query);
//        //拼接推送消息
//        Map<String, Object> params= BeanConvertUtils.convertBean(param.get("templateData"),Map.class);
////        String sms=MessageFormat.format(msgTemplate.getSmsSend(),  array);
//        String sms= StringSubstitutor.replace(msgTemplate.getSmsSend(), params);
//        log.info(sms);
//        //TODO 调取推送接口
//        sendMessageByUserId(param.get("userId").toString(),sms);
////        String userId=param.get("userId").toString();
////        Result result=userAppServiceClient.sendMessageByUserId(userId,sms);
//        //保存推送消息
//        MsgRecord msgRecord=new MsgRecord();
//        msgRecord.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
//        msgRecord.setMsg(sms);
//        msgRecord.setUserId(param.get("userId").toString());
//        msgRecord.setCreatTime(LocalDateTime.now());
//        msgRecordService.save(msgRecord);
//
//    }
    public void sendSubscript(String userId){
        Integer count=msgRecordService.getSubscript(userId,MsgRecord.SYSTEM_ALL);
        Integer deals=msgRecordService.getSubscript(userId,MsgRecord.SYSTEM_DEALS);
        Integer msg=msgRecordService.getSubscript(userId,MsgRecord.SYSTEM_MSG);
        Map<String, Integer> map= new HashMap<>();
        map.put(MessageConstants.SUBSCRIPT,count);
        map.put(MessageConstants.SUBSCRIPT_DEALS,deals);
        map.put(MessageConstants.SUBSCRIPT_MSG,msg);
        ResultMsg resultMsg=new ResultMsg();
        resultMsg.setCode(MessageConstants.SUBSCRIPT);
        resultMsg.setMessage(map);
        ChannelHandlerContext ctx=NettySendUtil.Verification(userId);
        if(ctx==null){
            return;
        }
        NettySendUtil.sendPointMessage(resultMsg,ctx);
    }
    /**
     * 发送剩余货源
     */
    public void residual(Map<String, Object> params){

        ResultMsg resultMsg=new ResultMsg();
        resultMsg.setCode(MessageConstants.CARGO_RESIDUAL);
        resultMsg.setMessage(params);
        NettySendUtil.sendAllMessage(resultMsg);
    }
}
